<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>拖拽属性</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        .box{
            width: 150px;
            height: 150px;
            margin-top: 30px;
            background-color: #f00;
        }

        .content {
            width: 300px;
            height: 200px;
            border: 2px solid #00f;
        }
    </style>
</head>
<body>
    <div class="content"></div>

    <!-- draggable="true" 后面的 ="true" 不能省略的 -->
    <div class="box" draggable="true"></div>

    <!-- 浏览器默认禁止元素堆叠，因此拖拽元素是黑色的圈，如果想让元素drop事件触发，需要在 dragover 事件中阻止默认事件
    
        dragstart  记录拖拽元素
        dragover  阻止默认
        drop  存放

        event.dataTransfer 拖拽事件中的传递数据
    -->

    <script type="text/javascript">
        var box = document.querySelector(".box"),
            content = document.querySelector(".content"),
            dragEle = null; // 拖拽元素

        // 设定draggable属性的元素是拖拽元素
        // dragstart drag dragleave dragend
        box.ondragstart = function (){
            console.log("开始拖拽");
            dragEle = this;

            // 设定传值数据
            event.dataTransfer.setData("text", "天王盖地虎");
        }

        // box.ondrag = function (){
        //     console.log("拖拽持续");
        // }

        box.ondragleave = function (){
            console.log("鼠标离开拖拽元素的身体");
        }

        box.ondragend = function (){
            console.log("结束拖拽");
        }

        // content 作为目标元素  dragenter dragover dragleave drop
        content.ondragenter = function (){
            console.log("鼠标携带拖拽元素进入content");
            this.style.borderColor = "#0f0";
        }

        content.ondragleave = function (){
            console.log("鼠标携带拖拽元素离开content");
            this.style.borderColor = "";
        }

        content.ondragover = function (){
            console.log("鼠标携带拖拽元素在content停留");
            // 阻止默认事件  event.stopPropagation()
            event.preventDefault();
        }

        content.ondrop = function (){
            console.log("鼠标在content中释放拖拽元素");
            this.append(dragEle);
            this.style.borderColor = "";

            // 获取传来的数据
            console.log("获取传递的数据", event.dataTransfer.getData("text"));
        }
    </script>
</body>
</html>